#include "CastErr.h"

#include <stdarg.h>
#include <string.h>
#include <fan-llvm/core/Core.h>
#include "Str.h"
#include "Type.h"


Type* CastErr_classType = NULL;
VTable* CastErr_classVTable = NULL;


/**********************************************
 *
 * Methods and fields
 *
 **********************************************/


/* Void make(Str msg, Err? cause) */
void CastErr_make_0(CastErr* self)
{
  CastErr_make(self, Str_defVal(), NULL);
}


/* Void make(Str msg, Err? cause) */
void CastErr_make_1(CastErr* self, Str* msg)
{
  CastErr_make(self, msg, NULL);
}


/* Void make(Str msg, Err? cause) */
void CastErr_make(CastErr* self, Str* msg, Err* cause)
{
  Err_make((Err*)self, msg, cause);
}


/**********************************************
 *
 * Extra methods
 *
 **********************************************/


/* Create a new CastErr instance and initialize it with CastErr_make() */
CastErr* CastErr_new(Str* msg, Err* cause)
{
  CastErr* err = (CastErr*)Obj_allocate(sizeof(CastErr), CastErr_classVTable);
  CastErr_make(err, msg, cause);
  return err;
}


/* Create a new CastErr instance and initialize it with the message given by the specified format.
 * 'msgFormat' uses the same format as Str_newWithFormat() */
CastErr* CastErr_newWithFormattedMsg(const char* msgFormat, ...)
{
  va_list args;
  va_start(args, msgFormat);
  Str* msg = Str_newWithFormatValist(msgFormat, args);
  va_end(args);
  return CastErr_new(msg, NULL);
}


/* Create a new CastErr instance to throw when casting an object from "fromType" to "toType" failed */
CastErr* CastErr_newWithTypes(Type* fromType, Type* toType)
{
  return CastErr_newWithFormattedMsg("%r cannot be cast to %r", fromType, toType);
}


/**********************************************
 *
 * Type-system functions
 *
 **********************************************/


Type* CastErr_initType(void)
{
  if (CastErr_classType == NULL)
  {
    Type* baseType = Err_initType();
    VTable* vtable = CastErr_initVTable();
    Type* type = Type_new("CastErr", baseType, vtable, sizeof(CastErr), sizeof(CastErrVTable));
    Type_registerCtorImplementation(type, "make", CastErr_make_0, 0);
    Type_registerCtorImplementation(type, "make", CastErr_make_1, 1);
    Type_registerCtorImplementation(type, "make", CastErr_make, 2);
    CastErr_classType = type;
    CastErr_initStatic();
  }
  return CastErr_classType;
}


VTable* CastErr_initVTable(void)
{
  if (CastErr_classVTable == NULL)
  {
    VTable* vtable = memoryAlloc(sizeof(CastErrVTable));
    memcpy(vtable, Err_initVTable(), sizeof(ErrVTable));
    CastErr_classVTable = vtable;
  }
  return CastErr_classVTable;
}


void CastErr_initStatic(void)
{
}
